import { Request, Response } from 'express';
import { QuestionService } from '../services/question-service';
import { CreateQuestionRequest, UpdateQuestionRequest, QuestionQueryParams } from '../models/Question';

export class QuestionController {
  // 获取问题列表
  public static async getQuestions(req: Request, res: Response): Promise<void> {
    try {
      const params: QuestionQueryParams = {
        page: parseInt(req.query.page as string) || 1,
        limit: parseInt(req.query.limit as string) || 10,
        status: req.query.status as string,
        priority: req.query.priority as string,
        userId: req.query.userId as string,
        search: req.query.search as string,
        sortBy: req.query.sortBy as any || 'createdAt',
        sortOrder: req.query.sortOrder as any || 'desc'
      };

      const result = await QuestionService.getQuestions(params);

      res.json({
        success: true,
        data: result,
      });
    } catch (error) {
      console.error('Error fetching questions:', error);
      res.status(500).json({
        success: false,
        message: '获取问题列表失败',
      });
    }
  }

  // 根据ID获取问题详情
  public static async getQuestionById(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const question = await QuestionService.getQuestionById(id);

      if (!question) {
        res.status(404).json({
          success: false,
          message: '问题不存在',
        });
        return;
      }

      // 增加浏览次数
      await QuestionService.incrementViewCount(id);

      res.json({
        success: true,
        data: question,
      });
    } catch (error) {
      console.error('Error fetching question:', error);
      res.status(500).json({
        success: false,
        message: '获取问题详情失败',
      });
    }
  }

  // 创建问题
  public static async createQuestion(req: Request, res: Response): Promise<void> {
    try {
      const questionData: CreateQuestionRequest = req.body;

      // 验证必填字段
      if (!questionData.title || !questionData.content || !questionData.userId) {
        res.status(400).json({
          success: false,
          message: '标题、内容和用户ID为必填字段',
        });
        return;
      }

      const question = await QuestionService.createQuestion(questionData);

      res.status(201).json({
        success: true,
        data: question,
        message: '问题创建成功',
      });
    } catch (error) {
      console.error('Error creating question:', error);
      res.status(500).json({
        success: false,
        message: '创建问题失败',
      });
    }
  }

  // 更新问题
  public static async updateQuestion(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const updateData: UpdateQuestionRequest = { ...req.body, id };

      const question = await QuestionService.updateQuestion(updateData);

      if (!question) {
        res.status(404).json({
          success: false,
          message: '问题不存在',
        });
        return;
      }

      res.json({
        success: true,
        data: question,
        message: '问题更新成功',
      });
    } catch (error) {
      console.error('Error updating question:', error);
      res.status(500).json({
        success: false,
        message: '更新问题失败',
      });
    }
  }

  // 删除问题
  public static async deleteQuestion(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const success = await QuestionService.deleteQuestion(id);

      if (!success) {
        res.status(404).json({
          success: false,
          message: '问题不存在或删除失败',
        });
        return;
      }

      res.json({
        success: true,
        message: '问题删除成功',
      });
    } catch (error) {
      console.error('Error deleting question:', error);
      res.status(500).json({
        success: false,
        message: '删除问题失败',
      });
    }
  }

  // 点赞问题
  public static async likeQuestion(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      await QuestionService.incrementLikeCount(id);

      res.json({
        success: true,
        message: '点赞成功',
      });
    } catch (error) {
      console.error('Error liking question:', error);
      res.status(500).json({
        success: false,
        message: '点赞失败',
      });
    }
  }

  // 取消点赞问题
  public static async unlikeQuestion(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      await QuestionService.decrementLikeCount(id);

      res.json({
        success: true,
        message: '取消点赞成功',
      });
    } catch (error) {
      console.error('Error unliking question:', error);
      res.status(500).json({
        success: false,
        message: '取消点赞失败',
      });
    }
  }

  // 获取用户的问题列表
  public static async getUserQuestions(req: Request, res: Response): Promise<void> {
    try {
      const { userId } = req.params;
      const params: QuestionQueryParams = {
        page: parseInt(req.query.page as string) || 1,
        limit: parseInt(req.query.limit as string) || 10,
        status: req.query.status as string,
        priority: req.query.priority as string,
        search: req.query.search as string,
        sortBy: req.query.sortBy as any || 'createdAt',
        sortOrder: req.query.sortOrder as any || 'desc'
      };

      const result = await QuestionService.getUserQuestions(userId, params);

      res.json({
        success: true,
        data: result,
      });
    } catch (error) {
      console.error('Error fetching user questions:', error);
      res.status(500).json({
        success: false,
        message: '获取用户问题列表失败',
      });
    }
  }

  // 获取热门问题
  public static async getPopularQuestions(req: Request, res: Response): Promise<void> {
    try {
      const limit = parseInt(req.query.limit as string) || 10;
      const questions = await QuestionService.getPopularQuestions(limit);

      res.json({
        success: true,
        data: questions,
      });
    } catch (error) {
      console.error('Error fetching popular questions:', error);
      res.status(500).json({
        success: false,
        message: '获取热门问题失败',
      });
    }
  }

  // 获取最新问题
  public static async getLatestQuestions(req: Request, res: Response): Promise<void> {
    try {
      const limit = parseInt(req.query.limit as string) || 10;
      const questions = await QuestionService.getLatestQuestions(limit);

      res.json({
        success: true,
        data: questions,
      });
    } catch (error) {
      console.error('Error fetching latest questions:', error);
      res.status(500).json({
        success: false,
        message: '获取最新问题失败',
      });
    }
  }
}